import { JSEncrypt } from './jsencrypt';

function utf8ByteLength(str) {
    let byteLength = 0;
    for (let i = 0; i < str.length; i++) {
        let charCode = str.charCodeAt(i);
        if (charCode <= 0x7F) {
            byteLength += 1;
        } else if (charCode <= 0x7FF) {
            byteLength += 2;
        } else if (charCode <= 0xFFFF) {
            byteLength += 3;
        } else {
            byteLength += 4;
        }
    }
    return byteLength;
}


/**
 * 生成密钥对
 */
export function generateKeyPair() {
    let jsEncrypt = new JSEncrypt();
    jsEncrypt.getKey();
    let json = {
        publicKey: jsEncrypt.getPublicKey(),
        privateKey: jsEncrypt.getPrivateKey()
    }
    // 去掉开头和结尾的换行符
    json.publicKey = json.publicKey.replace(/-----BEGIN PUBLIC KEY-----/, "");
    json.publicKey = json.publicKey.replace(/-----END PUBLIC KEY-----/, "");
    json.publicKey = json.publicKey.replace(/\n/, "");
    json.publicKey = json.publicKey.replace(/\n/, "");
    json.privateKey = json.privateKey.replace(/-----BEGIN RSA PRIVATE KEY-----/, "");
    json.privateKey = json.privateKey.replace(/-----END RSA PRIVATE KEY-----/, "");
    json.privateKey = json.privateKey.replace(/\n/, "").trim();
    json.privateKey = json.privateKey.replace(/\n/, "").trim();

    // 清洗字符串，移除所有非法字符
    json.publicKey = json.publicKey.replaceAll(/[^A-Za-z0-9+/=]/g, "");
    json.privateKey = json.privateKey.replaceAll(/[^A-Za-z0-9+/=]/g, "");


    return json;
}

/**
 * 加密
 * @param publicKey
 * @param encryptStr
 * @returns {string | false}
 */
function encrypt(publicKey,encryptStr) {
    let jsEncrypt = new JSEncrypt();
    jsEncrypt.setPublicKey(publicKey);
    // 获取字节数
    let byteLength = jsEncrypt.getKey().n.bitLength() / 8 - 11 - 1;

    // 获取encryptStr的字节数
    let encryptStrByteLength= utf8ByteLength(encryptStr);

    // 如果encryptStr的字节数小于字节数，直接加密
    if (encryptStrByteLength <= byteLength) {
        return jsEncrypt.encrypt(encryptStr);
    }
    // 如果encryptStr的字节数大于字节数，分段加密
    let result = "";
    let index = 0;
    while (index < encryptStr.length) {
        let lengthOfAdd = byteLength;
        let str = encryptStr.substring(index, lengthOfAdd+index);
        // 获取str中所有字符的字节数
        let strByteLengthList = [];
        for (let i = 0; i < str.length; i++) {
            strByteLengthList.push(utf8ByteLength(str[i]));
        }
        let subNum = 0;
        let subIndex = 0;
        for (let i = 0; i < strByteLengthList.length; i++) {
            subNum += strByteLengthList[i];
            if (subNum > byteLength) {
                break;
            }
            subIndex++;
        }
        lengthOfAdd = subIndex;

        str = encryptStr.substring(index, lengthOfAdd+index);

        console.log(str,"str",utf8ByteLength(str),"strByteLength")
        result += jsEncrypt.encrypt(str) + "&"
        index += lengthOfAdd;
    }
    // 去除最后的"&"
    result = result.substring(0, result.length - 1);
    return result;

}

/**
 * 解密
 */
function decrypt(privateKey,decryptStr) {
    let jsEncrypt = new JSEncrypt();
    jsEncrypt.setPrivateKey(privateKey);
    return jsEncrypt.decrypt(decryptStr);
}


export default {
    generateKeyPair,
    encrypt,
    decrypt
}